const { list } = require('./mock')
const OSS = require('ali-oss')
const path = require("path")

const AlipaySdk = require('alipay-sdk').default;
const AlipayFormData = require('alipay-sdk/lib/form').default;

const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();


const bodyParser = require('body-parser')
module.exports = app => {
	app.use(bodyParser.json())
	app.get('/api/list', (req, res) => {
		res.send({
			code: 200,
			data: list,
			message: '数据请求成功'
		})
	})


	app.get('/api/detail/:id', (req, res) => {
		const { id } = req.params
		const item = list.find(v => v.id === id);
		if (item) {
			res.send({
				code: 200,
				data: item,
				message: '数据请求成功'
			})
		} else {
			res.send({
				code: 404,
				data: null,
				message: '该商品已经下架'
			})
		}

	})


	// 支付下单接口--------链接支付宝----------沙箱测试
	app.post('/api/payment', (req, res) => {
		const { order_id, total_price, project, detail } = req.body


		const alipaySdk = new AlipaySdk({
			// 应用id
			appId: '2021000119601763',
			// 应用私钥
			privateKey: `MIIEowIBAAKCAQEAw8n+AicnWKCsuW0IaBaWBBU07cMuBLvDPG9AXjSOwIcEH9udgbwvLhYL2FNVL5icv9Dd/VxDBfh6ruNqovhatq1lX8psa32+MiuJbfVqysoxnuGboV9aXfl8XDcrrzW42JVkTzfy73PC6iOeccYH9YFzL8jJdQN4Iov9swAGVA7n87TkI/I+NhI/hz3bC7AXYjF9Ozi+/pXRel/YsptfmmHteSuQ9R1N7q1pQceuF5fSPh3eVEKn94OvO1fzmQdR0uBu3c0RFhWD1WaINsKSsSP0vihDUwNJK74XoTrbZVnvOhdpKTCH8sNqM8ST+M3UZ+WO/Ia1Q1imS1dMG6jM+QIDAQABAoIBAHeR7Kaz8ruVpOa5R+EJqiRkLyblhD0vzlQiPVVLE8NQsZwjK1YH72hd3m4GtoeS1GfwzyHkLqp+za3xBTbyJbRawQZ3QS+EY5uQKyYUM1wVj6hQcBNlgHLT4rcOmocub+0Vj2Ux7hN+xxLnHeSt5D5zCD2uihoEPGIczJt88GB0hi+JqZitGWs+X0voQouPusAfW4F/qN+mgcnxGrnQ/5raWTFOl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BCgKCAQEAqbGCyfTgKjeLLQWATqG606ZdhjhfSS3PxTYoUOEXRrlKZzHth2PQ6AAYBCi4VA6oKZcnXZUnD7ojlfjp0RcWGmhpre4XjPtpEK1jj8Kift/GrhA9iAdELjTTccUL/gfv74/POf4t0WjrLBoMk5MO4PkBx1n9ku63e8wsSjVaMxS9tzGXOCTaxFy36/WK7as6Hh/5MnNp9jKyUtLokRq92EloujRm+z93BaECnSG7xBwcCjbCxJ1yuRoVDsRsMHZJ7oWrQTbsmFy/i2suVGbIfSOZZDiGksw77FDd6TkvCLoS8cV8gGJ57BiQqa3Rqjro6/jvc7ByV1fOSxyXIMyuWQIDAQAB',
			// 支付宝网关
			gateway: 'https://openapi.alipaydev.com/gateway.do'
		});

		// 支付宝参数容器
		const formData = new AlipayFormData();
		// 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
		formData.setMethod('get');


		formData.addField('returnUrl', 'http://172.16.10.119/sso/');

		formData.addField('bizContent', {
			// 订单号
			outTradeNo: order_id,
			// 销售销售产品吗
			productCode: 'FAST_INSTANT_TRADE_PAY',
			// 金额
			totalAmount: total_price.toFixed(2),
			// 名字
			subject: project,
			// 详情
			body: detail,
		});

		const result = alipaySdk.exec(
			'alipay.trade.wap.pay',
			// 'alipay.trade.page.pay',
			{},
			{ formData: formData },
		);

		// result 为 url 链接
		result.then(url => {
			res.send({
				code: 200,
				data: {
					url: url
				},
				message: '下单成功, 请支付'
			})
		})
	})


	app.post('/upload', multipartMiddleware, function (req, res) {
		// req.files 保存文件
		
		// don't forget to delete all req.files when done
		const client = new OSS({
			// yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
			region: 'oss-cn-hangzhou',
			// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
			accessKeyId: 'LTAI5tBhcr12CEBRS4R9VHqf',
			accessKeySecret: 'EffrkOgX9I1FkZFZsMe89V9K7XTXYs',
			// 填写Bucket名称。
			bucket: '2005a-10',
		});

		const headers = {
			// 指定Object的存储类型。
			'x-oss-storage-class': 'Standard',
			// 指定Object的访问权限。
			'x-oss-object-acl': 'private',
			// 设置Object的标签，可同时设置多个标签。
			'x-oss-tagging': 'Tag1=1&Tag2=2',
			// 指定PutObject操作时是否覆盖同名目标Object。此处设置为true，表示禁止覆盖同名Object。
			'x-oss-forbid-overwrite': 'true',
		};

		try {
			// 填写OSS文件完整路径和本地文件的完整路径。OSS文件完整路径中不能包含Bucket名称。
			// 如果本地文件的完整路径中未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
			const result = client.put(req.files.file.originalFilename, path.normalize(req.files.file.path)
				// 自定义headers
				//,{headers}
			);
			result.then(resp => {
				res.send({
					code: 200,
					url: resp.url
				})
			})
		} catch (e) {
			res.send({
				code: 400,
				error: e
			})
		}
	});
}